﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Cm.Web.Common.Filter
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true);
            var isViewPage = attrs.Length == 1;//当前Action请求是否为具体的功能页
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                ViewResult vr = new ViewResult();
                vr.ViewName = "Error";
                filterContext.Result = vr;
            }
        }

        protected virtual bool HasAuthorize(ActionExecutingContext filterContext)
        {
            return false;
        }
        /// <summary>
        /// 判断当前是否是Ajax请求
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        protected virtual bool IsAjaxRequest(ActionExecutingContext filterContext)
        {
            var ajaxRequest = filterContext.HttpContext.Request.Headers["X-Requested-With"] != null;
            return ajaxRequest;
        }
    }

    /// <summary>
    /// 表示当前Action请求为一个具体的功能页面
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class ViewPageAttribute : Attribute
    {
    }
}
